#include <iostream>
#include <mysql/mysql.h>
using namespace std;

const string host = "127.0.0.1";
const string user = "connector";
const string password = "123456";
const string db = "conn";
const unsigned int port = 3306;

int main()
{
   // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;

    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        cout << "init失败" << endl;
        return 1;
    }
    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        cerr << "connect Mysql error" << endl;
    }
    // std::string sql;

    // while(true)
    // {
    //     std::cout << ">>>>";
    //     if(!getline(cin,sql)) break;
    //     if(sql == "quit") break;
    //     int n = mysql_query(my,sql.c_str());
    //     if(n==0)
    //     {
    //         cout << sql << " success:" << endl;
    //     }
    //     else
    //     {
    //         cerr << sql << "fail" <<endl;
    //     }
    // }
    // string sql = "update user set name = 'jimmm' where id = 1";
    // string sql = "insert into user(name,age,telephone) values('张三',19,'45678622345')";
    //string sql = "delete from user where id = 2";
    string sql = "select * from  user";
    int n = mysql_query(my,sql.c_str());
    if(n == 0)
    {
        cout << sql << " success" << endl;
    }
    else 
    {
        cout << sql << " fail" << endl;
        return 3;
    }
    MYSQL_RES* res = mysql_store_result(my);//转储表结构
    if(res == nullptr)
    {
        cerr << "mysql_store_result error" <<endl; 
        return 4;
    }

    int rows = mysql_num_rows(res);//提取行
    int fields = mysql_num_fields(res);//提取列

    cout << rows << " " << fields << endl;
    //提取属性
    MYSQL_FIELD* filed_arry = mysql_fetch_fields(res);
    for(int i = 0; i < fields; i++)
    {
        cout << filed_arry[i].name << "\t";
    }
    cout << "\n";
    for(int i = 0; i < rows ; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < fields; j++)
        {
            cout << row[j] << "\t";
        }
        cout << "\n";
    }

    // cout << "connect success" << endl;
    mysql_free_result(res);//释放结果集
    mysql_close(my);
    return 0;
}